package security.controller;


import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @GetMapping(value = "/r/r1", produces = {"text/plain;charset=UTF-8"})
    public String getR1(){
        return getUserName() + "访问资源1";
    }

    @GetMapping(value = "/r/r2", produces = {"text/plain;charset=UTF-8"})
    public String getR2(){
        return getUserName() + "访问资源2";
    }

    @PostMapping(value = "/login-success", produces = {"text/plain;charset=UTF-8"})
    public String loginSuccess(){
        return getUserName() + "登录成功";
    }

    public String getUserName(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof UserDetails){
            UserDetails user = (UserDetails) principal;
            String username = user.getUsername();
            return username;
        }else{
            return null;
        }
    }
}
